package user

import (
	"flag"
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
	"net/http"
	__ "srv/proto"
)

type Add struct {
	VideoName string `form:"videoName" json:"videoName" xml:"videoName"`
	Url       string `form:"url" json:"url" xml:"url"`
	UserId    int    `form:"userId" json:"userId" xml:"userId"`
	Location  string `form:"location" json:"location" xml:"location"`
	Tos       int8   `form:"tos" json:"tos" xml:"tos"`
}

const (
	defaultName = "world"
)

var (
	addr = flag.String("addr", "localhost:50051", "the address to connect to")
	name = flag.String("name", defaultName, "Name to greet")
)

func VideoAdd(c *gin.Context) {
	var json Add
	if err := c.ShouldBindJSON(&json); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	flag.Parse()
	// Set up a connection to the server.
	conn, err := grpc.NewClient(*addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	con := __.NewVideoServiceClient(conn)

	// Contact the server and print out its response.
	//ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	//defer cancel()
	r, err := con.VideoAdd(c, &__.VideoAddRequest{
		VideoName: json.VideoName,
		Url:       json.Url,
		UserId:    int64(json.UserId),
		Location:  json.Location,
		Tos:       int64(json.Tos),
	})
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}
	log.Printf("Greeting: %s", r.VideoId)
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "发布成功",
		"data":    r.VideoId,
	})
}
